package service

import (
	"ruoyi-go/app/admin/model/system"
	"ruoyi-go/app/admin/model/tools"
	"ruoyi-go/pkg/mysql"
	"ruoyi-go/utils"
)

var SysDictTypeService = &sysDictTypeService{}

type sysDictTypeService struct{}

// 分页查询
func (service sysDictTypeService) SelectSysDictTypeList(params tools.SearchTableDataParam, isPage bool) tools.TableDataInfo {
	var pageNum = params.PageNum
	var pageSize = params.PageSize
	sysDictType := params.Other.(system.SysDictType)
	offset := (pageNum - 1) * pageSize
	var total int64
	var rows []system.SysDictType

	var db = mysql.MysqlDb().Model(&rows)

	var dictName = sysDictType.DictName
	if dictName != "" {
		db.Where("dict_name like ?", "%"+dictName+"%")
	}

	var status = sysDictType.Status
	if status != "" {
		db.Where("status =", status)
	}

	var dictType = sysDictType.DictType
	if dictType != "" {
		db.Where("dict_type like ?", dictType)
	}

	var beginTime = params.Params.BeginTime
	var endTime = params.Params.EndTime

	if beginTime != "" {
		//Loc, _ := time.LoadLocation("Asia/Shanghai")
		//startTime1, _ := time.ParseInLocation(constants.DateFormat, beginTime, Loc)
		//endTime = endTime + " 23:59:59"
		//endTime1, _ := time.ParseInLocation(constants.TimeFormat, endTime, Loc)
		startTime1, endTime1 := utils.GetBeginAndEndTime(beginTime, endTime)
		db.Where("create_time >= ?", startTime1)
		db.Where("create_time <= ?", endTime1)
	}
	if err := db.Count(&total).Error; err != nil {
		return tools.Fail()
	}
	if isPage {
		if err := db.Limit(pageSize).Offset(offset).Find(&rows).Error; err != nil {
			return tools.Fail()
		}
	} else {
		if err := db.Find(&rows).Error; err != nil {
			return tools.Fail()
		}
	}

	if rows == nil {
		return tools.Fail()
	} else {
		return tools.Success(rows, total)
	}
}

func (service sysDictTypeService) FindTypeDictById(dictId string) system.SysDictType {
	var dictType system.SysDictType
	err := mysql.MysqlDb().Where("dict_id = ?", dictId).First(&dictType).Error
	if err != nil {
		panic(err.Error())
	}
	return dictType
}

func (service sysDictTypeService) SaveType(dictType system.SysDictType) {
	err := mysql.MysqlDb().Model(&system.SysDictType{}).Create(&dictType).Error
	if err != nil {
		panic(err.Error())
	}
}

func (service sysDictTypeService) UpdateType(dictType system.SysDictType) {
	err := mysql.MysqlDb().Updates(&dictType).Error
	if err != nil {
		panic(err.Error())
	}
}

func (service sysDictTypeService) DeleteDataType(dictIds string) {
	ids := utils.Split(dictIds)
	for i := 0; i < len(ids); i++ {
		id := ids[i]
		err := mysql.MysqlDb().Where("dict_id = ?", id).Delete(&system.SysDictType{}).Error
		if err != nil {
			panic(err.Error())
		}
	}
}

func (service sysDictTypeService) GetOptionSelect() []system.SysDictType {
	var dictType []system.SysDictType
	err := mysql.MysqlDb().Find(&dictType).Error
	if err != nil {
		panic(err.Error())
	}
	return dictType
}
